import { Controller,Get,Post, Put,Delete,Redirect, Param,Query, Body,HttpException,HttpStatus,ParseIntPipe,UseFilters  } from '@nestjs/common';
// import { Request,Response } from 'express';
import { Observable, of, throwError } from 'rxjs';
import { CreateNewsDto,UpdateNewsDto } from './dto/create-news.dto'
import { NewsService } from './news.service';
import { News } from './interfaces/news.interface';
import { HttpExceptionFilter } from '../http-exception.filter';
@Controller('news')
export class NewsController {
    constructor(private  newsService: NewsService) {}
    @Get('/page')
    @UseFilters( new HttpExceptionFilter())
    @UseFilters(HttpExceptionFilter)
    // @Redirect('https://nest.nodejs.cn')
    async getNewsPageList(@Query() query: string): Promise<News[]> {
        console.log(query);
        // 假如此时发生错误
        throw new HttpException('Forbidden',HttpStatus.FORBIDDEN)
        // 第一个参数是object
        throw new HttpException({
            status:HttpStatus.FORBIDDEN,
            error:'禁止访问'
        },HttpException.FORBIDDEN,{
            cause:'error'
        })
        // 
        return this.newsService.getNewsPageList();
    }

    @Post('/create')
   async  createNews(@Body() createNewsDto: CreateNewsDto) {
        console.log(createNewsDto,'添加参数');
        return this.newsService.createNews(createNewsDto);
    }

    @Get('/detail/:id')
    getNewsById(@Param('id',ParseIntPipe)id:number): string {
        console.log(id);
        return 'This is the news detail page';
    }

    // 异步 async 

    @Get('/async')
    async getNewsList(): Promise<string> {
        setTimeout(() => {
            console.log('This is the async news list');
        }, 2000);
        return 'This is the async news list';
    }

    // 异步 Observable 模式
    @Get('/observable')
    getNewsListObservable(): Observable<any[]> {
        return of([]);
    }



    @Put('/update/:id')
    updateNews(@Body() updateNewsDto: UpdateNewsDto): string {
        return 'This is the update news message';
    }

    @Delete('/delete/:id')
    deleteNews(): string {
        return 'This is the delete news message';   
    }

}
